package info.marlan.util;

import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.Thread.UncaughtExceptionHandler;

import android.app.Activity;
import android.content.Context;
import android.os.Build;

public class TopExceptionHandler implements UncaughtExceptionHandler {

	private Thread.UncaughtExceptionHandler defaultUEH;

	private Context app = null;

	public TopExceptionHandler(Context app) {
		this.defaultUEH = Thread.getDefaultUncaughtExceptionHandler();
		this.app = app;
	}

	public void uncaughtException(Thread t, Throwable e) {
		StackTraceElement[] arr = e.getStackTrace();
		String report = e.toString() + "\n\n";
		report += "--------- Stack trace ---------\n\n";
		for (int i = 0; i < arr.length; i++) {
			report += "    " + arr[i].toString() + "\n";
		}
		report += "-------------------------------\n\n";

		// If the exception was thrown in a background thread inside
		// AsyncTask, then the actual exception can be found with getCause
		report += "--------- Cause ---------\n\n";
		Throwable cause = e.getCause();
		if (cause != null) {
			report += cause.toString() + "\n\n";
			arr = cause.getStackTrace();
			for (int i = 0; i < arr.length; i++) {
				report += "    " + arr[i].toString() + "\n";
			}
		}
		report += "-------------------------------\n\n";
		report += "-------------------------------\n\n";
		report += "--------- Device ---------\n\n";
		report += "Brand: " + Build.BRAND + "\n";
		report += "Device: " + Build.DEVICE + "\n";
		report += "Model: " + Build.MODEL + "\n";
		report += "Id: " + Build.ID + "\n";
		report += "Product: " + Build.PRODUCT + "\n";
		report += "-------------------------------\n\n";
		report += "--------- Firmware ---------\n\n";
		report += "SDK: " + Build.VERSION.SDK + "\n";
		report += "Release: " + Build.VERSION.RELEASE + "\n";
		report += "Incremental: " + Build.VERSION.INCREMENTAL + "\n";
		report += "-------------------------------\n\n";
		try {
			FileOutputStream trace = app.openFileOutput("stack.trace",
					Context.MODE_PRIVATE);
			trace.write(report.getBytes());
			trace.close();
		} catch (IOException ioe) {
		
		}

		defaultUEH.uncaughtException(t, e);
	}
	

}
